package com.vilynn.interview.wechatofficial.sort;

import java.util.concurrent.Semaphore;

/**
 * Question1
 *
 * @author Weilin Wang
 * @since 2020/11/18
 */
public class Question1 {
    private static final String[] strings1 = "ABCD".split("");
    private static final String[] strings2 = "1234".split("");
    private static final Semaphore semaphore1 = new Semaphore(1);
    private static final Semaphore semaphore2 = new Semaphore(1);

    public static void main(String[] args) throws InterruptedException {

        semaphore2.acquire();
        new Thread(new MyThread(strings1, semaphore1, semaphore2)).start();
        new Thread(new MyThread(strings2, semaphore2, semaphore1)).start();
    }

    private static class MyThread implements Runnable {
        private String[] strings;
        private Semaphore semaphore1;
        private Semaphore semaphore2;

        public MyThread(String[] strings, Semaphore semaphore1, Semaphore semaphore2) {
            this.strings = strings;
            this.semaphore1 = semaphore1;
            this.semaphore2 = semaphore2;
        }

        @Override
        public void run() {
            Thread t = Thread.currentThread();
            for (int i = 0; i < strings.length; i++) {
                try {
                    semaphore1.acquire();
                    System.out.println(String.format("id:%s name:%s 输出%s", t.getId(), t.getName(), strings[i]));
                    semaphore2.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }
}
